package com.msh.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msh.common.VMSystem;
import com.msh.entity.OrderCollectEntity;
import com.msh.entity.OrderEntity;
import com.msh.feignService.UserService;
import com.msh.feignService.VMService;
import com.msh.service.OrderCollectService;
import com.msh.service.OrderService;
import com.msh.viewmodel.PartnerViewModel;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @author :zhangchuanfu
 * @Date :2023/2/2
 * @Time :22:36
 * @description :订单合并任务
 */
@Component
@Slf4j
public class OrderCollectJob {

    @Autowired
    private OrderService orderService;
    @Autowired
    private VMService vmService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderCollectService orderCollectService;
    /**
     * 订单合并
     * @param param
     * @return
     */
    @XxlJob("orderCollectJobHandler")
    public ReturnT<String> collectTask(String param) {
        LocalDate yesterday = LocalDate.now().plusDays(-1);
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.select("owner_id","node_id","IFNULL(sum(amount),0) as amount","IFNULL(sum(bill),0) as bill","IFNULL(count(1),0) as price")
                .lambda().ge(OrderEntity::getCreateTime,yesterday)
                .lt(OrderEntity::getCreateTime,LocalDate.now())
                .eq(OrderEntity::getPayStatus, VMSystem.PAY_STATUS_PAYED)
                .groupBy(OrderEntity::getOwnerId,OrderEntity::getNodeId);
        orderService.list(qw).forEach(order->{
            OrderCollectEntity orderCollectEntity = new OrderCollectEntity();
            orderCollectEntity.setDate(yesterday);
            orderCollectEntity.setNodeId(order.getNodeId());
            orderCollectEntity.setNodeName(vmService.getNodeName(order.getNodeId()));

            orderCollectEntity.setOwnerId(order.getOwnerId());
            PartnerViewModel partner = userService.getPartner(order.getOwnerId());
            orderCollectEntity.setOwnerName(partner.getName());

            orderCollectEntity.setOrderTotalMoney(order.getAmount());//金额
            orderCollectEntity.setTotalBill(order.getBill());//分成
            orderCollectEntity.setOrderCount(order.getPrice());//订单数量(借用价格字段)
            orderCollectEntity.setRatio(partner.getRatio());//分成比例
            orderCollectService.save(orderCollectEntity);
        });
        return ReturnT.SUCCESS;
    }
}
